@page
@using EasyAbp.EShop.Plugins.Baskets
@using EasyAbp.EShop.Plugins.Baskets.Localization
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Mvc.Localization
@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal
@using Volo.Abp.Settings
@inject IHtmlLocalizer<BasketsResource> L
@inject IAuthorizationService _authorizationService
@inject ISettingProvider _settingProvider
@model EasyAbp.EShop.Plugins.Baskets.Web.Pages.EShop.Plugins.Baskets.BasketItems.BasketItem.CreateModalModel
@{
    Layout = null;
}

<abp-dynamic-form abp-model="ViewModel" data-ajaxForm="true" asp-page="CreateModal">
    <abp-modal>
        <abp-modal-header title="@L["CreateBasketItem"].Value"></abp-modal-header>
        <abp-modal-body>
            <abp-form-content />
        </abp-modal-body>
        <abp-modal-footer buttons="@(AbpModalButtons.Cancel|AbpModalButtons.Save)"></abp-modal-footer>
    </abp-modal>
</abp-dynamic-form>

<script>
    var localStorageItemKey = localStorageItemKey || "EShopBasket:" + basketName;
    var l = abp.localization.getResource('EasyAbpEShopPluginsBaskets');

    $(document).ready(function() {
        if (@(Model.ServerSide ? "true" : "false")) return;
        
        function generateClientSideData(formObj) {
            var basketItemService = easyAbp.eShop.plugins.baskets.basketItems.basketItem;

            basketItemService.generateClientSideData({ items: [ formObj.viewModel ] }, {
                success: function (responseText, statusText, xhr, form) {
                    var basketItems = JSON.parse(localStorage.getItem(localStorageItemKey)) || [];
                    basketItems = pushOrUpdateBasketItem(basketItems, responseText.items[0])
                    localStorage.setItem(localStorageItemKey, JSON.stringify(basketItems));
                    $form.trigger('abp-ajax-success',
                    {
                        responseText: responseText,
                        statusText: statusText,
                        xhr: xhr,
                        $form: form
                    })
                }
            });
        }
        
        var $form = $("form");
        $form.off('submit');
        $form.on('submit', function(e){
            e.preventDefault();
            var orderService = easyAbp.eShop.orders.orders.order;
            var formObj = $form.serializeFormToObject();
            if (abp.currentUser.isAuthenticated) {
                orderService.checkCreate({
                    storeId: formObj.viewModel.storeId,
                    orderLines: [{
                        productId: formObj.viewModel.productId,
                        productSkuId: formObj.viewModel.productSkuId,
                        quantity: formObj.viewModel.quantity
                    }]
                }, {
                    success: function (responseText, statusText, xhr, form) {
                        if (responseText.canCreate) {
                            generateClientSideData(formObj);
                        } else {
                            abp.message.error(l('@BasketsErrorCodes.CheckCreateOrderFailed', responseText.reason));
                        }
                    }
                });
            } else {
                generateClientSideData(formObj);
            }
        });
    });
    
    function pushOrUpdateBasketItem(basketItems, item) {
        var index = basketItems.findIndex(x => x.storeId === item.storeId && x.productId === item.productId && x.productSkuId === item.productSkuId);
        if (index >= 0) {
            basketItems[index].quantity += item.quantity;
        } else {
            basketItems.push(item);
        }
        
        return basketItems;
    }
</script>